<template>
	<div class="app-container">
		<div class="emp-container">
			<div class="left-box">
				<div class="header-box">
					<div class="header-box-title">
						<span class="el-icon-menu item-gap"></span>
						<span>部门</span>
					</div>
				</div>
				<div class="left-box-content">
					<el-tree
						class="left-box-content-inner"
						highlight-current
						default-expand-all
						node-key="id"
						:data="deptList"
						:props="{
							children: 'children',
							label: 'name'
						}"
						@node-click="onSelectDept"
					/>
				</div>
			</div>
			<div class="right-box">
				<div ref="searchBar" class="header-box">
					<div class="flex-start-center-wrap">
						<jk-add-button class="item-gap" :permission-prefix="prefix" @click="onAddBtn" />
						<el-button-group class="item-gap flex-center">
							<el-tooltip class="item" effect="dark" content="导入" placement="top-start">
								<el-button type="primary" icon="el-icon-upload2" size="small" @click="importDialogState = true"></el-button>
							</el-tooltip>
							<el-tooltip class="item" effect="dark" content="导出" placement="top-start">
								<el-button :loading="exportLoading" size="small" type="primary" icon="el-icon-download" @click="onExportExcel"></el-button>
							</el-tooltip>
						</el-button-group>
						<!--<el-button size="small" type="primary" :loading="syncBtnLoading" @click="onSyncBtn">同步ERP</el-button>-->
					</div>
					<div class="flex-end-center">
						<el-checkbox v-model="searchParams.onJob" size="small" class="item-gap" border>在职</el-checkbox>
						<jk-select v-model="searchParams.groupId" :option-list="groupList" class="search-bar-item-size2 item-gap" placeholder="班组" />
						<jk-search-input v-model="searchParams.nameOrCode" class="search-bar-item-size3 item-gap" placeholder="员工姓名或编号" @on-enter="onSearchBtn" />
						<jk-search-button size="small" type="primary" icon="el-icon-search" @click="onSearchBtn">搜索</jk-search-button>
					</div>
				</div>
				<div class="right-box-content">
					<jk-table ref="jkTable" :loading="tableLoading" :data="tableData" border :height="tableHeight - 44">
						<vxe-table-column field="name" align="center" title="头像" fixed="left" width="60">
							<template #default="scope">
								<div class="row-emp-avatar">
									<el-avatar shape="square" size="small" icon="el-icon-user-solid"></el-avatar>
									<div :class="scope.row.gender ? 'sex-icon row-emp-man el-icon-male' : 'sex-icon row-emp-woman el-icon-female'"></div>
								</div>
							</template>
						</vxe-table-column>
						<vxe-table-column field="name" title="姓名" fixed="left" :width="80"></vxe-table-column>
						<vxe-table-column field="code" title="编号" :min-width="100" />
						<vxe-table-column field="postName" title="岗位" :min-width="100" />
						<vxe-table-column field="groupName" title="班组" :min-width="100" />
						<vxe-table-column field="workshopName" title="区域" :min-width="80" />
						<vxe-table-column field="deptName" title="所属部门" :min-width="100" />
						<vxe-table-column field="mobile" title="电话" :min-width="120" />
						<vxe-table-column field="leaderName" title="直接上级" :width="90" />
						<vxe-table-column field="creatorName" title="创建人" :width="100" />
						<vxe-table-column field="createTime" title="创建时间" :width="160" />
						<vxe-table-column field="updaterName" title="修改人" :width="100" />
						<vxe-table-column field="updateTime" title="修改时间" :width="160" />
						<vxe-table-column field="onJob" title="状态" width="80" align="center">
							<template #default="scope">
								<emp-status :status="scope.row.onJob"></emp-status>
							</template>
						</vxe-table-column>
						<vxe-table-column align="center" title="操作" fixed="right" width="170">
							<template #default="scope">
								<div class="flex-center">
									<jk-edit-button class="item-gap" :permission-prefix="prefix" @click="onEditData(scope.row.id)" />
									<el-dropdown trigger="click" @command="onDropdownChange($event, scope.row)">
										<el-button type="primary" size="mini" class="el-dropdown-link">
											更多<i class="el-icon-arrow-down el-icon--right"></i>
										</el-button>
										<el-dropdown-menu slot="dropdown">
											<el-dropdown-item
												v-for="(item) in dropdownOption"
												:key="item.code"
												:command="item.code"
												:divided="item.divided"
												:disabled="item.allowState || item.allowState === false ? scope.row.onJob !== item.allowState : false"
												:style="{
													'display': !item.isShow ? 'none' : 'block',
													'text-decoration': getPermission([`${prefix}:${item.permissionName}`]) ? '' : 'line-through'
												}"
											>
												<span :class="`${item.icon} item-gap`"></span>
												<span>{{ item.name }}</span>
											</el-dropdown-item>
										</el-dropdown-menu>
									</el-dropdown>
								</div>
							</template>
						</vxe-table-column>
					</jk-table>
					<footer ref="pageBar" class="flex-end-center margin-top-10">
						<jk-page
							:page-index="searchParams.pageNo"
							:page-sizes="searchParams.pageSizes"
							:page-size="searchParams.pageSize"
							:total="searchParams.count"
							@on-change="onPageChange"
						/>
					</footer>
				</div>
			</div>
			<save-dialog
				:dept-id="selectDeptId"
				:dialog-state="saveDialogState"
				:data-id="dataId"
				@on-visible-change="onVisibleChangeOfSaveDialog"
				@on-confirm="onConfirmButtonSaveDialog"
			/>
			<detail-dialog
				:data-id="detailId"
				:dialog-state="detailDialogState"
				@on-visible-change="onDetailDialogVisibleChange"
			/>
			<import-dialog
				:dialog-state="importDialogState"
				@on-visible-change="onVisibleChangeOfImportDialog"
				@on-finish="onFinishBtnOfImportDialog"
			></import-dialog>
		</div>
	</div>
</template>

<script>
    import saveDialog from './save-dialog';
    import detailDialog from './detail-dialog';
    import { deleteEmp, getEmpPage } from '@/api/system/emp';
    import { createTree, pageConfig, tipsBar } from '../../../utils/jk/jk-tool';
    import { listDept } from '../../../api/system/dept';
    import calHeight from '../../../mixins/cal-table-height';
    import empStatus from './components/emp-status';
    import importDialog from './import-dialog';
    import permissionMixin from '../../../mixins/permission-mixin';
    import { systemEmpUpdateJob } from '../../../api/system/emp';
    import { personnelGroupPage } from '../../../api/personnel/group';
    export default {
        name: 'Emp',
        components: {
            detailDialog,
            saveDialog,
            empStatus,
            importDialog
        },
        mixins: [calHeight, permissionMixin],
        data() {
            return {
                prefix: 'personnel:emp',
                searchParams: {
                    count: 0,
                    pageNo: pageConfig.pageNo,
                    pageSize: pageConfig.pageSize,
                    onJob: true,
                    nameOrCode: ''
                },
                groupList: [],
                searchDept: '',
                exportLoading: false,
                dataId: null,
                tableData: [],
                saveDialogState: false,
                tableLoading: false,
                deptList: [],
                rootId: null,
                deptId: null,
                selectDeptId: null,
                detailId: null,
                detailDialogState: false,
                importDialogState: false,
                dropdownOption: [
                    { code: 'DETAIL', name: '详情', isShow: true, permissionName: 'query', icon: 'el-icon-view', allowState: null, api: null },
                    { code: 'REINSTATED', name: '复职', isShow: true, permissionName: 'update', icon: 'el-icon-user-solid', allowState: false, api: systemEmpUpdateJob },
                    { code: 'DEPART', name: '离职', isShow: true, permissionName: 'update', icon: 'el-icon-user', allowState: true, api: systemEmpUpdateJob },
                    { code: 'DELETE', name: '删除', isShow: true, permissionName: 'delete', icon: 'el-icon-delete', allowState: null, api: deleteEmp }
                ],
                syncBtnLoading: false
            };
        },
        methods: {
            /* onSyncBtn() {
                this.syncBtnLoading = true;
                workforceManagementScheduleEmpSynchronizedDl().then(res => {
                    this.syncBtnLoading = false;
                    if (res.data.status === 200) {
                        if (res.data.res) {
                            tipsBar(this, 'custom', 'success', '同步成功!');
                        } else {
                            tipsBar(this, 'custom', 'error', '同步失败!');
                        }
                    }
                });
            },*/
            onDropdownChange(type, row) {
                const optionItem = this.dropdownOption.find(x => x.code === type);
                if (this.getPermission([`${this.prefix}:${optionItem.permissionName}`])) {
                    if (optionItem) {
                        if (optionItem.code === 'DETAIL') {
                            this.detailId = row.id;
                            this.detailDialogState = true;
                        } else if (optionItem.code === 'DELETE') {
                            this.$confirm(`确定"${optionItem.name}"吗？`, '提示', { type: 'warning' }).then(() => {
                                optionItem.api(row.id).then(res => {
                                    if (res.data.status === 200) {
                                        this.getListRequest();
                                    }
                                });
                            }).catch(() => {});
                        } else {
                            this.$confirm(`确定"${optionItem.name}"吗？`, '提示', { type: 'warning' }).then(() => {
                                optionItem.api({ id: row.id }).then(res => {
                                    if (res.data.status === 200) {
                                        this.getListRequest();
                                    }
                                });
                            }).catch(() => {});
                        }
                    }
                } else {
                    tipsBar(this, 'custom', 'warning', '无操作权限!');
                }
            },
            onVisibleChangeOfImportDialog(e) {
                this.importDialogState = e;
            },
            onFinishBtnOfImportDialog() {
                this.importDialogState = false;
                this.getListRequest();
            },
            onPageChange(pageIndex, pageSize) {
                this.searchParams.pageNo = pageIndex;
                this.searchParams.pageSize = pageSize;
                this.getListRequest();
            },
            clearCacheMethod() {
                // Object.assign(this.$data, this.$options.data());
                this.getDependentData();
            },
            setList(arr) {
                const [one, ...rest] = arr;
                const keys = Object.keys(one);
                const newRest = rest.map(item => {
                    const newObj = {};
                    keys.map(key => {
                        newObj[one[key]] = item[key];
                    });
                    return newObj;
                });
                return newRest;
            },
            onExportExcel() {
                this.exportLoading = true;
                getEmpPage({
                    onJob: this.searchParams.onJob,
                    name: this.searchParams.nameOrCode,
                    deptId: this.deptId
                }).then(res => {
                    if (res.data.status === 200) {
                    import('@/vendor/Export2Excel').then(excel => {
                        const titleList = ['姓名', '编号', '身份证号', '办公电话', '电话', '性别', '班组', '区域', '直接上级', '所属部门', '岗位', '描述', '状态'];
                        const keyList = ['name', 'code', 'idCard', 'tel', 'mobile', 'gender', 'groupName', 'workshopName', 'leaderName', 'deptName', 'postName', 'remark', 'onJob'];
                        const dataList = JSON.parse(JSON.stringify(res.data.res)).map(item => {
                            item.onJob ? item.onJob = '在职' : item.onJob = '离职';
                            parseFloat(item.gender) ? item.gender = '男' : item.gender = '女';
                            return item;
                        });
                        const data = dataList.map(v => keyList.map(j => v[j]));
                        excel.export_json_to_excel({
                            header: titleList,
                            data,
                            filename: '员工管理',
                            autoWidth: true,
                            bookType: 'xlsx'
                        });
                    });
                    }
                    this.exportLoading = false;
                });
            },
            onDetailDialogVisibleChange(e) {
                if (!e) {
                    this.detailId = null;
                }
                this.detailDialogState = e;
            },
            getGroupListRequest() {
                return personnelGroupPage({
                    auditState: 1
                }).then(res => {
                    if (res.data.status === 200) {
                        this.groupList = res.data.res || [];
                    }
                });
            },
            async getDependentData() {
                this.tableLoading = true;
                await this.getDeptListRequest();
                await this.getGroupListRequest();
                await this.getListRequest();
                this.tableLoading = false;
            },
            getDeptListRequest() {
                return listDept({ status: 1, name: this.searchDept }).then(res => {
                    if (res.data.status === 200) {
                        this.deptList = createTree(res.data.res, {});
                    }
                });
            },
            onSelectDept(e) {
                this.deptId = e.id;
                if (e.children && e.children.length !== 0) {
                    this.selectDeptId = null;
                } else {
                    this.selectDeptId = e.id;
                }
                this.getListRequest();
            },
            onEditData(id) {
                this.dataId = id;
                this.saveDialogState = true;
            },
            onConfirmButtonSaveDialog() {
                this.saveDialogState = false;
                this.dataId = null;
                this.getListRequest();
            },
            onAddBtn() {
                this.saveDialogState = true;
            },
            onVisibleChangeOfSaveDialog(e) {
                this.saveDialogState = e;
                if (!e) {
                    this.dataId = null;
                }
            },
            getListRequest() {
                this.tableLoading = true;
                return getEmpPage({
                    ...this.searchParams,
                    deptId: this.deptId
                }).then(res => {
                    this.tableLoading = false;
                    if (res.data.status === 200) {
                        this.tableData = res.data.res;
                        this.searchParams.count = res.data.count;
                    }
                });
            },
            onSearchBtn() {
                this.searchParams.pageNo = 1;
                this.searchParams.count = 1;
                this.getListRequest();
            }
        },
        mounted() {
            this.getDependentData();
        }
    };
</script>
<style lang="scss" scoped>
$left_box_width: 220px;
$header_height: 48px;
.row-emp-avatar {
    position: relative;
    display: flex;
    align-items: center;
    justify-content: center;
}
.row-emp-woman {
    color: hotpink;
}
.sex-icon {
    position: absolute;
    right: -4px;
    top: -4px;
}
.row-emp-man {
    color: #2d8cf0;
}
.emp-container {
    display: flex;
    border: solid 1px #eee;
    border-radius: 4px;
    overflow: hidden;
    .header-box {
        height: $header_height;
        border-bottom: solid 1px #eee;
        display: flex;
        justify-content: space-between;
        align-items: center;
        padding: 0 12px;
        .header-box-title {
            color: #515a6e;
            font-size: 18px;
        }
    }
    .left-box {
        width: $left_box_width;
        height: calc(100vh - 120px);
        background: #fff;
        overflow: hidden;
        border-right: solid 1px #eee;
        .left-box-content {
            height: calc(100% - #{$header_height});
            padding: 12px 12px 12px;
            .left-box-content-inner {
                height: 100%;
                overflow: auto;
                border-radius: 4px;
            }
        }
    }
    .right-box {
        width: calc(100% - #{$left_box_width});
        background: #fff;
        .right-box-content {
            padding: 12px;
        }
    }
}

</style>
